package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.common.utils.DownloadUtil;
import com.itheima.common.utils.UtilFuns;
import com.itheima.domain.cargo.Contract;
import com.itheima.domain.cargo.ContractExample;
import com.itheima.vo.ContractProductVo;
import com.itheima.service.cargo.ContractService;
import com.itheima.web.controller.BaseController;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController {

    @Reference
    private ContractService contractService;

    @RequestMapping(value = "/printExcel",name = "提交下载出货表--模板样式")
    public void printExcel(String inputDate) throws IOException
    {
        //获取出货表信息
        List<ContractProductVo> contractProductVos = contractService.findByShipTime(inputDate,getCurrentUserCompanyId());
        //将数据封装到excel
        int rowNum = 0;
        String path = session.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx");
        Workbook workbook = new XSSFWorkbook(path);
        Sheet sheet = workbook.getSheetAt(0);
        //设置标题
        Row row1 = sheet.getRow(rowNum++);
        Cell cell = row1.getCell(1);
        // 2015-01月份出货表   要的是----------->   2015年1月份出货表
        cell.setCellValue((inputDate).replace("-0","-").replace("-","年")+"月份出货表");
        //创建字段
        rowNum++;
        //设置字段样式
        CellStyle[] css= new CellStyle[9];
        Row row = sheet.getRow(rowNum); //获取了第三行
        for(int i=1;i<row.getLastCellNum();i++){
            css[i]=row.getCell(i).getCellStyle();//将原来excel中第三行的每一个样式保存到了数组中
        }
        //将contractProductVos封装处理
        for (ContractProductVo vo : contractProductVos) {
            int cellNum = 1;
            Row row_content = sheet.createRow(rowNum++);//内容行

            Cell cell1 = row_content.createCell(cellNum++);
            cell1.setCellValue(vo.getCustomName());//客户
            cell1.setCellStyle(css[1]);

            Cell cell2 = row_content.createCell(cellNum++);
            cell2.setCellValue(vo.getContractNo());//订单号
            cell2.setCellStyle(css[2]);

            Cell cell3 = row_content.createCell(cellNum++);
            cell3.setCellValue(vo.getProductNo());//货号
            cell3.setCellStyle(css[3]);

            Cell cell4 = row_content.createCell(cellNum++);
            cell4.setCellValue(vo.getCnumber());//数量
            cell4.setCellStyle(css[4]);

            Cell cell5 = row_content.createCell(cellNum++);
            cell5.setCellValue(vo.getFactoryName());//厂家名称
            cell5.setCellStyle(css[5]);

            Cell cell6 = row_content.createCell(cellNum++);
            Date deliveryPeriod = vo.getDeliveryPeriod();//交货期限
            cell6.setCellValue(new SimpleDateFormat("yyyy/MM/dd").format(deliveryPeriod));
            cell6.setCellStyle(css[6]);

            Cell cell7 = row_content.createCell(cellNum++);
            cell7.setCellValue(new SimpleDateFormat("yyyy/MM/dd").format(vo.getShipTime()));//船期
            cell7.setCellStyle(css[7]);

            Cell cell8 = row_content.createCell(cellNum++);
            cell8.setCellValue(vo.getTradeTerms());//贸易条款
            cell8.setCellStyle(css[8]);
        }
        //下载
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        workbook.write(stream);//将excel内容写入到baos中
        new DownloadUtil().download(stream,response,"出货表.xlsx");

    }

    //提交下载出货表--自定义样式
   /* @RequestMapping("/printExce2")
    public void printExce2(String inputDate) throws IOException {
        //获取出货表信息
        List<ContractProductVo> contractProductVos = contractService.findByShipTime(inputDate,getCurrentUserCompanyId());
        //将数据封装到excel
        int rowNum = 0;
        Workbook workbook = new XSSFWorkbook();//创建workbook
        Sheet sheet = workbook.createSheet();//创建sheet
        //设置所有的列宽
        sheet.setColumnWidth(0,6*256);
        sheet.setColumnWidth(1,26*256);
        sheet.setColumnWidth(2,12*256);
        sheet.setColumnWidth(3,30*256);
        sheet.setColumnWidth(4,12*256);
        sheet.setColumnWidth(5,15*256);
        sheet.setColumnWidth(6,10*256);
        sheet.setColumnWidth(7,10*256);
        sheet.setColumnWidth(8,10*256);
        //设置标题
        Row row_title = sheet.createRow(rowNum++);
        Cell cell = row_title.createCell(1);
        // 2015-01月份出货表   要的是----------->   2015年1月份出货表
        cell.setCellValue((inputDate).replace("0-","-").replace("-","年")+"月份出货表");

        //设置标题样式
        cell.setCellStyle(bigTitle(workbook));
        //合并单元格 参数1 开始行  参数2 结束行  参数3 开始列  参数4  结束列
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
        //设置字段
        Row row_little = sheet.createRow(rowNum++);

        String [] little_row = {"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        for (int i = 0; i < little_row.length; i++) {
            Cell cell1 = row_little.createCell(i + 1);
            cell1.setCellValue(little_row[i]);
            cell1.setCellStyle(title(workbook));//设置字段的样式
        }

        //将contractProductVos封装处理
        for (ContractProductVo vo : contractProductVos) {
            int cellNum = 0;
            Row row_content = sheet.createRow(rowNum++);//内容行

            Cell cell1 = row_content.createCell(cellNum++);
            cell1.setCellValue(vo.getCustomName());//客户
            cell1.setCellStyle(text(workbook));

            Cell cell2 = row_content.createCell(cellNum++);
            cell2.setCellValue(vo.getContractNo());//订单号
            cell2.setCellStyle(text(workbook));

            Cell cell3 = row_content.createCell(cellNum++);
            cell3.setCellValue(vo.getProductNo());//货号
            cell3.setCellStyle(text(workbook));

            Cell cell4 = row_content.createCell(cellNum++);
            cell4.setCellValue(vo.getCnumber());//数量
            cell4.setCellStyle(text(workbook));

            Cell cell5 = row_content.createCell(cellNum++);
            cell5.setCellValue(vo.getFactoryName());//厂家名称
            cell5.setCellStyle(text(workbook));

            Cell cell6 = row_content.createCell(cellNum++);
            cell6.setCellValue(vo.getDeliveryPeriod());//交货期限
            cell6.setCellStyle(text(workbook));

            Cell cell7 = row_content.createCell(cellNum++);
            cell7.setCellValue(vo.getShipTime());//船期
            cell7.setCellStyle(text(workbook));

            Cell cell8 = row_content.createCell(cellNum++);
            cell8.setCellValue(vo.getTradeTerms());//贸易条款
            cell8.setCellStyle(text(workbook));

        }
        //下载
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        workbook.write(stream);//将excel内容写入到baos中
        new DownloadUtil().download(stream,response,"出货表.xlsx");

    }*/

    //提交下载出货表--没有样式
    /*@RequestMapping("/printExcel1")
    public void printExcel1(String inputDate) throws IOException {
        //获取出货表信息
        List<ContractProductVo> contractProductVos = contractService.findByShipTime(inputDate,getCurrentUserCompanyId());
        //将数据封装到excel
        int rowNum = 0;
        Workbook workbook = new XSSFWorkbook();//创建workbook
        Sheet sheet = workbook.createSheet();//创建sheet
        //设置标题
        Row row_title = sheet.createRow(rowNum++);
        Cell cell = row_title.createCell(1);
        cell.setCellValue(inputDate+"月份出货表");

        //设置字段
        Row row_little = sheet.createRow(rowNum++);
        String [] little_row = {"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        for (int i = 0; i < little_row.length; i++) {
            Cell cell1 = row_little.createCell(i + 1);
            cell1.setCellValue(little_row[i]);
        }

        //将contractProductVos封装处理
        for (ContractProductVo vo : contractProductVos) {
            int cellNum = 0;
            Row row_content = sheet.createRow(rowNum++);//内容行

            Cell cell1 = row_content.createCell(cellNum++);
            cell1.setCellValue(vo.getCustomName());//客户

            Cell cell2 = row_content.createCell(cellNum++);
            cell2.setCellValue(vo.getContractNo());//订单号

            Cell cell3 = row_content.createCell(cellNum++);
            cell3.setCellValue(vo.getProductNo());//货号

            Cell cell4 = row_content.createCell(cellNum++);
            cell4.setCellValue(vo.getCnumber());//数量

            Cell cell5 = row_content.createCell(cellNum++);
            cell5.setCellValue(vo.getFactoryName());//厂家名称

            Cell cell6 = row_content.createCell(cellNum++);
            cell6.setCellValue(vo.getDeliveryPeriod());//交货期限

            Cell cell7 = row_content.createCell(cellNum++);
            cell7.setCellValue(vo.getShipTime());//船期

            Cell cell8 = row_content.createCell(cellNum++);
            cell8.setCellValue(vo.getTradeTerms());//贸易条款

        }
        //下载
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        workbook.write(stream);//将excel内容写入到baos中
        new DownloadUtil().download(stream,response,"出货表.xlsx");

    }*/

    @RequestMapping(value = "/print",name = "前往出货表")
    public String print(){
        return "cargo/print/contract-print";
    }

    @RequestMapping(value = "/list",name = "分页查询")
    public String list(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int size){
        //创建条件查询对象
        ContractExample example = new ContractExample();
        //添加排序条件
        example.setOrderByClause("create_time desc");
        //设置查询条件：企业id等于当前登录用户的企业id
        example.createCriteria().andCompanyIdEqualTo(super.getCurrentUserCompanyId());
        //掉用service查询
        PageInfo pageInfo = contractService.findAll(example, page, size);
        //存到请求域中
        request.setAttribute("page",pageInfo);
        //返回前往购销合同列表
        return "cargo/contract/contract-list";
    }

    @RequestMapping(value = "/toAdd",name = "前往保存页面")
    public String toAdd(){

        return "cargo/contract/contract-add";
    }

    @RequestMapping(value = "/edit",name = "保存或更新")
    public String edit(Contract contract){

        if(UtilFuns.isEmpty(contract.getId())){
            //设置用户的所属企业信息
            contract.setCompanyId(super.getCurrentUserCompanyId());
            contract.setCompanyName(super.getCurrenUserCompanyName());
            //调用业务层保存
            contractService.save(contract);
        }else {
            //更新
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/toUpdate",name = "前往更新页面")
    public String toUpdate(String id){

        Contract contract = contractService.findById(id);
        request.setAttribute("contract",contract);

        return "cargo/contract/contract-update";
    }

    @RequestMapping(value = "/delete",name = "删除")
    public String delete(String id){
        contractService.delete(id);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/toView",name = "查看")
    public String toView(String id){
        Contract contract = contractService.findById(id);
        request.setAttribute("contract",contract);
        return "cargo/contract/contract-view";
    }

    @RequestMapping(value = "/submit",name = "提交为已上报")
    public String submit(String id){
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(1);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/checkUpdateState",name = "验证是否允许提交或取消")
    public @ResponseBody String checkUpdateState(String id){
        Contract contract = contractService.findById(id);
        if(contract.getState()>1){
            return "0";//不允许提交或取消
        }else {
            return "1";//可以提交或者取消
        }
    }

    @RequestMapping(value = "/cancel",name = "取消提交")
    public String cancel(String id){
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(0);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }



    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }
}
